package com.taoist_awei.blog.infrastructure.repository;

import com.taoist_awei.blog.core.ClassifyEntity;
import com.taoist_awei.blog.core.ClassifyNode;
import com.taoist_awei.blog.core.ClassifyRepository;
import com.taoist_awei.blog.infrastructure.mapper.ClassifyMapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.*;

@Repository
public class MyBatisClassifyRepository implements ClassifyRepository {
    @Autowired
    private ClassifyMapper mapper;

    @Override
    public void addClassify(ClassifyEntity entity) {
        mapper.insertClassify(entity);
    }

    @Override
    public void removeClassifyById(String classifyId) {
        //这里查到classifyId得所有子节点并且删除
        mapper.deleteClassify(classifyId);
    }

    @Override
    public Optional<List<ClassifyNode>> getClassifyTree() {
        List<ClassifyEntity> list = mapper.getClassifyList();
        Map<String, ClassifyNode> nodeMap = new HashMap<>();
        List<ClassifyNode> resultNodeList = new ArrayList<>();
        Set<String> idSet = new HashSet<>();

        for (ClassifyEntity entity : list) {
            ClassifyNode node = new ClassifyNode(
                    entity.getClassifyId(),
                    entity.getClassifyName(),
                    entity.getFatherId(),
                    entity.getArticleNum()
            );
            nodeMap.put(entity.getClassifyId(), node);
        }
        for (Map.Entry<String, ClassifyNode> entry : nodeMap.entrySet()) {
            ClassifyNode node = entry.getValue();
            String fatherId = node.getFatherId();
            String nodeId = node.getClassifyId();
            if (idSet.contains(nodeId)) continue;
            if (fatherId != null && !fatherId.equals("")) {
                nodeMap.get(fatherId).addChild(node);
                idSet.add(nodeId);
            }
        }
        idSet.forEach(id-> {
            nodeMap.remove(id);
        });

        nodeMap.forEach((key, value)-> {
            resultNodeList.add(value);
        });

        return Optional.ofNullable(resultNodeList);
    }

    @Override
    public Optional<ClassifyEntity> getClassifyById(String classifyId) {
        return Optional.empty();
    }


    @Override
    public void updateClassify(ClassifyEntity entity) {

    }
}
